#!/usr/bin/env python
# -*- coding: utf-8 -*-

import gtk

from modules.pad_editor import Pad_editor

def save_file(str, absname):
    """
    @todo:编码
    """
    save_file = open(absname, 'w')
    save_file.write(str)
    save_file.close()

def creat_new_editor(editor, notebook):
    """
    将editor加入到notebook中
    @param editor:
    @param notebook:
    @type editor:Pad_editor
    @type notebook:Pad_notebook
    """
    notebook.append_page_and_editor(editor)
    notebook.set_current_page(-1)

def open_file_creat_new_editor(notebook, absname):
    """
    根据absname建立editor并加入到notebook中
    """
    try:
        if notebook.find_pos_with_abs_filename(absname) == None:
            "如果要打开的文件不再列表中"
            file = open(absname, 'r')
            text = file.read()
            file.close()

            new_editor = Pad_editor(absname, text, False, False)

            editor_list = notebook.get_editor_list()
            if ((len(editor_list) == 1) and
                (editor_list[-1].is_temp() == True) and
                (editor_list[-1].is_change() == False) ):
                "只有一个未修改的临时文件"
                notebook.remove_page_and_editor(editor_list[-1])
                creat_new_editor(new_editor, notebook)
            else:
                creat_new_editor(new_editor, notebook)
        else:
            notebook.set_current_page(notebook.find_pos_with_abs_filename(absname))
    except Exception, e:
        print e
        gtk.MessageDialog(#parent = self.__mainwindow,
                            flags = gtk.DIALOG_MODAL,
                            message_format = 'Error:\n    File open fail'
                            ).show()